package com.sky.controller;

import com.sky.constant.MessageConstant;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.GModelService;
import com.sky.utils.ModelUtils;
import com.sky.dto.PredictModelDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/models")
@Slf4j
@Api(tags = "模型接口")
public class GModelController {
  @Autowired
  GModelService gModelService;


  @GetMapping("/showinfo")
  @ApiOperation("分页获取模型信息")
  public Result<PageResult> getModelsInfo(Integer page,Integer pageSize){
    PageResult pageResult=gModelService.pageQueryModels(page,pageSize);
    return Result.success(pageResult);
  }

  @GetMapping("/recordsinfo")
  @ApiOperation("分页获取训练模型历史记录信息")
  public Result<PageResult> getRecordsInfo(Integer page,Integer pageSize){
    PageResult pageResult=gModelService.pageQueryRecords(page,pageSize);
    return Result.success(pageResult);
  }
  @GetMapping("/recordsinfolimit")
  @ApiOperation("分页获取训练模型历史记录信息, 根据文件名准确搜索")
  public Result<PageResult> getRecordsInfoLimit(Integer page,Integer pageSize,String fileName){
    if(fileName==null || fileName.length()==0){
      Result.error(MessageConstant.WRONG_FILE_NAME);
    }
    PageResult pageResult=gModelService.pageQueryRecordsLimit(page,pageSize,fileName);
    return Result.success(pageResult);
  }
  @ApiOperation("预测模型")
  @PostMapping(value="/upload")
  public Result<Integer> handleFileUpload(PredictModelDTO predictModelDTO) {

    if(!(predictModelDTO.getLimit()<1 && predictModelDTO.getLimit() > 0) ){
      return Result.error(MessageConstant.LIMIT_ERROR);
    }

    if (predictModelDTO.getMultipartFiles() == null || predictModelDTO.getMultipartFiles() .length == 0) {
      return Result.error(MessageConstant.FILE_EMPTY);
    }

    try {
      // 指定存储文件的目录
      String uploadDir = ModelUtils.originDataPath;
      File dir = new File(uploadDir);
      if (!dir.exists()) {
        dir.mkdirs();
      }
      // 存文件
      for (MultipartFile file : predictModelDTO.getMultipartFiles() ) {
        // 获取上传文件的原始名称
        String fileName = file.getOriginalFilename();
        // 构建存储路径
        File destFile = new File(uploadDir + fileName);
        // 将上传的文件保存到指定目录
        file.transferTo(destFile);
      }
      // 预测文件
      // 存文件
      int tranId=-1;
      for (MultipartFile file : predictModelDTO.getMultipartFiles() ) {
        // 获取上传文件的原始名称
        String fileName = file.getOriginalFilename();
        tranId = gModelService.predictModels(fileName,predictModelDTO.getLimit());
      }
      return Result.success(tranId);
    } catch (IOException e) {
      e.printStackTrace();
      return Result.error(MessageConstant.FILE_NOT_SAVE);
    }
  }

  @ApiOperation("删除记录")
  @PostMapping(value = "/deleterecord")
  public Result deleteRecord(Integer tranId){
    gModelService.deleteRecord(tranId);
    return Result.success();
  }

  @ApiOperation("获取模型文件结果")
  @GetMapping("/downloadresult")
  @ResponseBody
  public ResponseEntity<Resource> downloadFile(int tranId) {
    String fileName = gModelService.selectRecord(tranId);
    Path filePath = Paths.get(ModelUtils.resultDataPath).resolve(fileName).normalize();
    try {
      Resource resource = new org.springframework.core.io.UrlResource(filePath.toUri());
      if (resource.exists() || resource.isReadable()) {
        return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);
      } else {
        return ResponseEntity.notFound().build();
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      return ResponseEntity.status(500).build();
    }
  }

}
